//
//  ZYComposeViewController.swift
//  weibo007
//
//  Created by 陈宗毅 on 15/12/27.
//  Copyright © 2015年 czy. All rights reserved.
//

import UIKit
import SVProgressHUD

class ZYComposeViewController: UIViewController {

    /// toolBar底部约束
    private var toolBarBottomCon : NSLayoutConstraint?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        prepareUI()
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //弹出键盘
        textView.becomeFirstResponder()
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func willChangeFrame(notification:NSNotification){
        print("notification:\(notification)")
       
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSTimeInterval
        
       let frame = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        //改变toolBar底部的约束
        toolBarBottomCon?.constant = -(UIScreen.mainScreen().bounds.height - frame.origin.y)
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
    }
    
    private func prepareUI(){
        
        self.view.backgroundColor = UIColor.whiteColor()
        setupNavigationBar()
        setupTextView()
        setupToolBar()
        
        
    }
    ///设置导航栏
   private func setupNavigationBar(){
    //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancel")
    //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "send")
    //让右边的按钮不可用
    navigationItem.rightBarButtonItem?.enabled = false
    
        setupNavTitle()
    

    }
    
    func cancel(){
        SVProgressHUD.dismiss()
        //取消第一响应者
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func send(){
        let text = textView.emoticonText()
        //提示用户正在发送微博
        SVProgressHUD.showWithStatus("正在发送微博。。。")
        ZYNetworkTool.shareInstance.sendStatus(text) { (result, error) -> () in
            if error != nil {
                print("error:\(error)")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                
            }
            //发送成功
            SVProgressHUD.showSuccessWithStatus("微博发送成功")
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                self.cancel()
            })
        }
        
    }
    
    ///设置导航栏标题
    
    private func setupNavTitle(){
        let prefix = "发微博"
        
        if let name = ZYUserAccount.loadUserAccount()?.screen_name{
            
            let label = UILabel()
            label.numberOfLines = 0
            label.textAlignment = NSTextAlignment.Center
            label.font = UIFont.systemFontOfSize(14)
            label.textColor = UIColor.blackColor()
            
            let text = prefix + "\n" + name
            
            let nameRange = (text as NSString).rangeOfString(name)
          let textAtt =   NSMutableAttributedString(string: text)
            textAtt.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(11), range: nameRange)
            textAtt.addAttribute(NSForegroundColorAttributeName, value: UIColor.lightGrayColor(), range: nameRange)
            label.attributedText = textAtt
            
            label.sizeToFit()
            
            navigationItem.titleView = label
            
        }else
        {
            navigationItem.title = prefix
        }
        
        
    }
    
    ///设置toolBar
    private func setupToolBar(){
    
        view.addSubview(toolBar)
     let cons =   toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
       
        toolBarBottomCon = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        
        //添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_addbutton_background", "action": "add"]]
        
        var items = [UIBarButtonItem]()
        var index = 0
        for dict in itemSettings
        {
            let imageName = dict["imageName"]!
            
            let action = dict["action"]!
            
            let item = UIBarButtonItem(imageName: imageName)
            
          let button = item.customView as! UIButton
            button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            button.tag = index
            
            items.append(item)
            
            //添加弹簧
          let FlexibleSpace =   UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            
            items.append(FlexibleSpace)
            
            index++
        }
        
        items.removeLast()
        
        toolBar.items = items
    }
    
   private func setupTextView(){
        textView.delegate = self
    
    view.addSubview(textView)
    
        textView.ff_Fill(view)
    
    }
    
    func picture()
    {
        print("图片")
    }
    
    func mention()
    {
        print("@")
    }
    
    func trend()
    {
        print("#")
    }
   
    
    func add()
    {
        print("add")
    }
    ///切换键盘
    func emoticon(){
        print("text.inputView:\(textView.inputView)")
        
        textView.resignFirstResponder()
        //延迟 弹出键盘
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            // 如果使用的是系统键盘,就切换到我们的键盘,如果使用的是我们的键盘就切换到系统
            self.textView.inputView = self.textView.inputView == nil ? self.emoticonVC.view : nil
            
            //再次弹出键盘
            self.textView.becomeFirstResponder()
        }
        
    }
    
    //MARK: - 懒加载
    private lazy var toolBar:UIToolbar = {
    
        let toolBar = UIToolbar()
        
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1)
        
        return toolBar
    }()
    
    private lazy var textView:ZYPlaceholderTextView = {
    
        let textView = ZYPlaceholderTextView()
        textView.backgroundColor = UIColor.brownColor()
        textView.font = UIFont.systemFontOfSize(18)
        textView.alwaysBounceVertical = true
        textView.placeholderText = "分享新鲜事"
        
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag

        return textView
        
    }()
    
    private lazy var emoticonVC:ZYEmoticonViewController = ZYEmoticonViewController(textView: self.textView)

}

extension ZYComposeViewController:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        //设置导航栏右边按钮的可用和不可用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
